<?php

/**
 * Image Plugin
 * @author ReGeDa
 */
class Image extends Plugin_Object {

	/**
	 * Constructor
	 */
	public function  __construct() {
		parent::__construct();
		platcode()->lang->load('image_lib');
	}

	/**
	 * Get image information
	 * @param string $filename
	 * @return array
	 */
	private function get_info($filename) {

		// fetch image size
		list($width, $height) = getimagesize($filename);

		// result
		return array(
			'width' => $width,
			'height' => $height,
			'type' => exif_imagetype($filename)
		);
	}

	/**
	 * Validate an image
	 * @param string $filename
	 * @param array $check
	 * @return array|boolean
	 */
	public function validate($filename, $check = array()) {


		$info = $this->get_info($filename);

		// image validator
		foreach ($check as $validator => $param) {

			$method = 'check_'.$validator;

			// check
			if ( ! $this->$method($param, $info)) {

				// language property
				$lang = 'image_'.$validator;

				platcode()->raw['err'] = sprintf(platcode()->lang->$lang, $param);
				return FALSE;
			}
		}

		// success
		return $info;
	}

	/**
	 * Resize an image
	 * @param string $filename
	 * @param array $config - [size|ratio_width|ratio_height, height, width, type]
	 */
	public function resize($filename, $config = array()) {

		// square
		if (array_key_exists('size', $config)) {
			$h = $w = $config['size'];
		}
		// ratio width
		else if (array_key_exists('ratio_width', $config)) {
			$w = $config['ratio_width'];
			$h = round($config['height'] * $w / $config['width']);
		}
		// ratio height
		else if (array_key_exists('ratio_height', $config)) {
			$h = $config['ratio_height'];
			$w = round($config['width'] * $h / $config['height']);
		}

		// if need to resize
		if ($h != $config['height'] && $w != $config['width']) {

			$type = image_type_to_extension($config['type'], FALSE);

			////////// READ
			// new image resource
			$dst = imagecreatetruecolor($w, $h);
			// source image
			$src = call_user_func('imagecreatefrom'.$type, $filename);

			///////// RESIZE
			imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $config['width'], $config['height']);
			// free source
			imagedestroy($src);

			///////// WRITE
			call_user_func_array('image'.$type, array($dst, $filename));
			// free destination
			imagedestroy($dst);
		}
	}

	/**
	 * Check min size for square image
	 * @param integer $size
	 * @param array $info
	 * @return boolean
	 */
	protected function check_min_size($size, $info) {
		return $info['width'] == $info['height'] && $info['width'] >= $size;
	}

}

// end of file